package com.glsc.ngateway.platform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.PageConstant;
import com.glsc.ngateway.common.api.common.enums.PlatformConstant;
import com.glsc.ngateway.common.api.common.enums.SystemConfigCodeConstant;
import com.glsc.ngateway.common.api.ldap.dto.LdapUserDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.oaflow.dto.oa.OaLinkDto;
import com.glsc.ngateway.common.api.platform.dto.LoginUserDto;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.annotation.PageAccessAnnotation;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Role;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.UserMenuInfo;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.api.common.utils.encrypt.AESEncrypt;
import com.glsc.ngateway.common.api.common.utils.encrypt.RSAEncrypt;
import com.glsc.ngateway.platform.aspect.JwtHelper;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.*;
import com.glsc.ngateway.platform.utils.JsonTool;
import com.glsc.ngateway.platform.utils.SpecificationFactory;
import com.glsc.ngateway.platform.utils.SpecificationFactory.SpecElement;
import com.glsc.ngateway.platform.utils.SpecificationFactory.Type;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.ROLE_OPEARATOR;

/**
 * 功能描述: <br>
 *
 * @author gaojc
 * @date 2020/9/3 10:37
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;
    private RoleService roleService;
    private UserCache userCache;
    /*
        private UserActionLogRepo userActionLogRepo;
    */
    private UserActionService userActionService;


    private LdapService ldapService;


    Logger logger = LoggerFactory.getLogger(UserController.class);


    @Resource
    private IFeignLdapService feignLdapService;

    @Value("#{'${role.array}'.split(',')}")
    private List<String> rolesa;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    public void setLdapService(LdapService ldapService) {
        this.ldapService = ldapService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Autowired
    public void setUserCache(UserCache userCache) {
        this.userCache = userCache;
    }

/*
    @Autowired
    public void setUserActionLogRepo(UserActionLogRepo userActionLogRepo) {
        this.userActionLogRepo = userActionLogRepo;
    }
*/

    @Autowired
    public void setUserActionService(UserActionService userActionService) {
        this.userActionService = userActionService;
    }

    @PageAccessAnnotation(operMenu = "权限管理-用户管理", operType = "新建", operDesc = "新建用户")
    @PostMapping("/create")
    @ApiOperation(value = "新增用户")
    public PlatformResponse<Void> create(@RequestBody User user) throws Exception {
        String newPassword = Strings.isNotBlank(user.getPassword()) ? RSAEncrypt.decrypt(user.getPassword(), PlatformConstant.RSA_PRIVATE_KEY) :
                Optional.ofNullable(systemConfigService.findByCode(SystemConfigCodeConstant.PASSWORD_DEFAULT)).orElseThrow(() -> PlatformException.error("无默认密码，请配置")).getConfigValue();
        user.setPassword(newPassword);
        userService.add(user);
        return PlatformResponse.successMsg("创建成功");
    }

    @PageAccessAnnotation(operMenu = "权限管理-用户管理", operType = "编辑", operDesc = "编辑用户")
    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息")
    public PlatformResponse<Void> update(@RequestBody User user) throws Exception {

        User orgUser = userService.findByIdAll(user.getId());
        if (orgUser == null) {
            return PlatformResponse.failedMsg("未找到该有效用户,id=" + user.getId());
        }
        if (user.getPassword() != null) {
            String newPassword = user.getPassword();
            user.setPassword(RSAEncrypt.decrypt(newPassword, PlatformConstant.RSA_PRIVATE_KEY));
        }
        userService.update(user);
        return PlatformResponse.successMsg("更新成功");
    }

    @PageAccessAnnotation(operMenu = "权限管理-用户管理", operType = "删除", operDesc = "删除用户")
    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    public PlatformResponse<Void> delete(@RequestBody String id) {
        Long uid = JsonTool.parseJsonId(id);
        if (uid == null) {
            return PlatformResponse.failedMsg("id不能为空");
        }
        if (userService.delete(uid) == 1) {
            return PlatformResponse.successMsg("删除成功");
        } else {
            return PlatformResponse.failedMsg("未找到id=" + uid + "的用户");
        }
    }

    @GetMapping("/findbyid")
    @ApiOperation(value = "根据id查找用户")
    public PlatformResponse<User> findById(@RequestParam("id") long id) {
        User user = userService.findById(id);
        if (user == null) {
            return PlatformResponse.failedMsg("未找到id=" + id + "的用户");
        }
        return PlatformResponse.successData(user);
    }

    @GetMapping("/findByUserName")
    @ApiOperation(value = "根据用户名查找用户")
    public PlatformResponse<String> findByUserName(@RequestParam("userName") String userName) {
        PlatformUserDto user = userService.findByUsername(userName);
        if (user == null) {
            return PlatformResponse.failedMsg("未找到userName=" + userName + "的用户");
        }
        return PlatformResponse.successData(user.getName());
    }

    @GetMapping("/findByAccount")
    @ApiOperation(value = "根据用户名查找用户")
    public PlatformResponse<PlatformUserDto> findByAccount(@RequestParam("account") String account) {
        PlatformUserDto user = userService.findByUsername(account);
        if (user == null) {
            return PlatformResponse.failedMsg("未找到userName=" + account + "的用户");
        }
        return PlatformResponse.successData(user);
    }

    @GetMapping("/findbyroleid")
    @ApiOperation(value = "根据角色id查找用户")
    public PlatformResponse<List<User>> findByRoleId(
            @RequestParam("roleId") long roleId,
            @ApiParam(value = "登录账号") @RequestParam(required = false) String username,
            @ApiParam(value = "用户名字") @RequestParam(required = false) String name) {
        List<User> list = userService.findByRoleId(roleId);
        List<User> data = list.stream().filter(user -> {
            boolean b = true;
            if (username != null && !username.isEmpty()) {
                b = username.equals(user.getUsername());
                if (!b) {
                    return false;
                }
            }
            if (name != null && !name.isEmpty()) {
                b = user.getName().contains(name);
            }
            return b;
        }).collect(Collectors.toList());
        return PlatformResponse.successData(data);
    }

    @PageAccessAnnotation(operMenu = "配置管理-邮件订阅管理", operType = "报表订阅查询", operDesc = "查看报表订阅用户")
    @GetMapping("/findbyreportid")
    @ApiOperation(value = "根据报表id查找用户")
    public PlatformResponse<List<User>> findByReportId(
            @RequestParam("reportId") String reportId) {
        List<User> list = userService.findByReportId(reportId);
        list.forEach(value ->
        {
            value.setPassword(null);
            value.setRoles(null);
        });
        return PlatformResponse.successData(list);
    }


    @PageAccessAnnotation(operMenu = "权限管理-用户管理", operType = "查看", operDesc = "用户列表")
    @GetMapping("/listpage")
    @ApiOperation(value = "查询用户分页")
    public PlatformResponse<Page<User>> listpage(
            @ApiParam(value = "登录账号") @RequestParam(required = false) String username,
            @ApiParam(value = "用户名字") @RequestParam(required = false) String name,
            @ApiParam(value = "部门") @RequestParam(required = false) String userDepartment,
            @ApiParam(value = "备注") @RequestParam(required = false) String remark,
            @ApiParam(value = "用户类型") @RequestParam(required = false) String userType,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
        // SpecElement deletedE = new SpecElement(Type.EQ, "deleted", 0);
        SpecElement usernameE = new SpecElement(Type.EQ, "username", Strings.isNotBlank(username) ? username : null);
        SpecElement nameE = new SpecElement(Type.LIKE, "name", Strings.isNotBlank(name) ? name : null);
        SpecElement depE = new SpecElement(Type.EQ, "userDepartment", Strings.isNotBlank(userDepartment) ? userDepartment : null);
        SpecElement remarkE = new SpecElement(Type.LIKE, "remark", Strings.isNotBlank(remark) ? remark : null);
        SpecElement userTypeE = new SpecElement(Type.EQ, "userType", Strings.isNotBlank(userType) ? userType : null);
        Specification spec = SpecificationFactory.build(SpecificationFactory.OP.AND, usernameE, nameE, userTypeE, remarkE, depE);
        pageNo = Objects.nonNull(pageNo) ? pageNo : PageConstant.PageNo;
        pageSize = Objects.nonNull(pageSize) ? pageSize : PageConstant.PageSize;
        Page<User> page = userService.findPage(spec, pageNo, pageSize);

        return PlatformResponse.successData(page);
    }

    @PageAccessAnnotation(operMenu = "权限管理-产品授权", operType = "查询", operDesc = "用户列表")
    @GetMapping("/listpagenoc")
    @ApiOperation(value = "查询不含当前用户的用户分页")
    public PlatformResponse<Page<User>> listpagenoc(
            @ApiParam(value = "登录账号") @RequestParam(required = false) String username,
            @ApiParam(value = "用户名字") @RequestParam(required = false) String name,
            @ApiParam(value = "用户类型") @RequestParam(required = false) String userType,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request) {
        if (username != null && username.isEmpty()) {
            username = null;
        }
        if (name != null && name.isEmpty()) {
            name = null;
        }
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = PageConstant.PageSize;
        }
        PlatformUserDto user = userCache.get(request);

        SpecElement idE = new SpecElement(Type.NEQ, "id", user.getId());
        SpecElement usernameE = new SpecElement(Type.EQ, "username", username);
        SpecElement nameE = new SpecElement(Type.LIKE, "name", name);
        SpecElement deletedE = new SpecElement(Type.EQ, "deleted", 0);
        SpecElement userTypeE = new SpecElement(Type.EQ, "userType", userType);
        Specification spec = SpecificationFactory.build(SpecificationFactory.OP.AND, idE, usernameE, nameE, userTypeE, deletedE);
        //即将废弃admin，所以此处不影响
        if (!"admin".equals(user.getUsername().toLowerCase())) {
            spec = spec.and((root, query, builder) ->
                    builder.notEqual(root.get("username"), "admin")
            );
        }
        Page<User> page = userService.findPage(spec, pageNo, pageSize);
        page.getContent().forEach(k ->
        {
            Set<String> roleNames = k.getRoles().stream().map(role -> role.getName()).collect(Collectors.toSet());
            if (!Collections.disjoint(roleNames, rolesa)) {
                k.setDisable(1);
            }
        });

        return PlatformResponse.successData(page);
    }

    @PageAccessAnnotation(operMenu = "配置管理-邮件订阅管理", operType = "用户订阅查询", operDesc = "用户列表")
    @GetMapping("/listpageactive")
    @ApiOperation(value = "邮件订阅用户分页")
    public PlatformResponse<Page<User>> listpageactive(
            @ApiParam(value = "登录账号") @RequestParam(required = false) String username,
            @ApiParam(value = "用户名字") @RequestParam(required = false) String name,
            @ApiParam(value = "用户类型") @RequestParam(required = false) String userType,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request) {
        if (username != null && username.isEmpty()) {
            username = null;
        }
        if (name != null && name.isEmpty()) {
            name = null;
        }

        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = PageConstant.PageSize;
        }
        PlatformUserDto user = userCache.get(request);
        Set<String> userRoleNames = new HashSet<>(user.getRoles());

        SpecElement usernameE = new SpecElement(Type.EQ, "username", username);
        SpecElement nameE = new SpecElement(Type.LIKE, "name", name);
        SpecElement deletedE = new SpecElement(Type.EQ, "deleted", 0);
        SpecElement userTypeE = new SpecElement(Type.EQ, "userType", userType);
        Specification spec = SpecificationFactory.build(SpecificationFactory.OP.AND, usernameE, nameE, userTypeE, deletedE);
        if (!"admin".equals(user.getUsername().toLowerCase())
            || !userRoleNames.contains(ROLE_OPEARATOR)) {
            spec = spec.and((root, query, builder) ->
                    builder.notEqual(root.get("username"), "admin")
            );
        }
        Page<User> page = userService.findPage(spec, pageNo, pageSize);
        page.getContent().forEach(k ->
        {
            Set<String> roleNames = k.getRoles().stream().map(role -> role.getName()).collect(Collectors.toSet());
            if (!Collections.disjoint(roleNames, rolesa)) {
                k.setDisable(1);
            }
        });
        return PlatformResponse.successData(page);
    }

    //@PageAccessAnnotation(operMenu = "用户登陆",operType = "用户登陆",operDesc = "用户登陆")
    @PostMapping("/login")
    public PlatformResponse<PlatformUserDto> login(@RequestBody PlatformUserDto userDto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //校验验证码
        String rightCode = (String) request.getSession().getAttribute("rightCode");
        String tryCode = userDto.getTryCode();
        //系统用户不校验验证码
        if (!userService.isSysUser(userDto.getUsername())) {
            if (ObjectUtils.isEmpty(rightCode) || ObjectUtils.isEmpty(userDto.getTryCode()) || !rightCode.equals(userDto.getTryCode())) {
                return PlatformResponse.failedMsg("验证码错误!");
            }
        }
        logger.info("用户请求认证，用户名为：" + userDto.getUsername() + ",密码为：" + userDto.getPassword() + ",认证时间为：" + System.currentTimeMillis());
        //解密密码
        String password = RSAEncrypt.decrypt(userDto.getPassword(), PlatformConstant.RSA_PRIVATE_KEY);
        PlatformUserDto res = null;
        //判断是否本地登录
        if (userService.needLoginLocal(userDto.getUsername())) {
            //本地登录，查找t_user
            res = userService.loginLocal(userDto.getUsername(), password);
            res.setToken(JwtHelper.generateToken(userDto.getUsername()));
        } else {
            //非本地登录，请求ldap登录
            logger.info("调用Feign认证接口,调用时间为：" + System.currentTimeMillis());
            // ldap 用户名与密码验证
            String tokenTemp = feignLdapService.login(LdapUserDto.builder()
                    .userName(userDto.getUsername())
                    .password(userDto.getPassword())
                    .systemId("glgateway")
                    .build());
            logger.info("完成Feign认证接口调用," + tokenTemp + ",完成时间为：" + System.currentTimeMillis());
            String token = parseToken(tokenTemp);
            logger.info("完成Token解析,完成时间为：" + System.currentTimeMillis());
            if (token.equals(PlatformConstant.RETURN_TOK_ERROR)) {
                return PlatformResponse.failedMsg("用户名或者密码错误!");
            }
            res = userService.login(userDto.getUsername());
            res.setToken(token);
        }
        //设置网盘session
//        OwncloudUtils.getSessionCookie(userDto.getUsername(), password, response);
//        res.setAuthorization("Basic " + Base64.encode(userDto.getUsername() + ":" + password));
        res.setUrls(null);
        return PlatformResponse.successData(res);
    }

    @PageAccessAnnotation(operMenu = "权限管理-用户管理", operType = "角色分配", operDesc = "设置用户角色")
    @PostMapping("/setroles")
    @ApiOperation(value = "设置用户的角色")
    public PlatformResponse<Void> setRoles(@ApiParam(required = true, value = "用户设置角色") @RequestBody String jsonStr) {
        JsonObject json = JsonParser.parseString(jsonStr).getAsJsonObject();
        JsonElement userIdE = json.get("userId");
        if (null == userIdE || userIdE.getAsLong() < 0) {
            return PlatformResponse.failedMsg("userId 参数错误");
        }
        User user = userService.findById(userIdE.getAsLong());
        if (null == user) {
            return PlatformResponse.failedMsg("用户不存在");
        }
        JsonArray jsonArray = json.get("roles").getAsJsonArray();
        Set<Role> roles = new HashSet<>();
        jsonArray.forEach(object -> {
            long roleId = object.getAsJsonObject().get("roleId").getAsLong();
            Role role = roleService.findById(roleId);
            if (null != role) {
                roles.add(role);
            }
        });
        user.setRoles(roles);
        userService.save(user);

        return PlatformResponse.successMsg("角色设置成功");
    }

    //@PageAccessAnnotation(operMenu = "用户信息获取",operType = "用户信息获取",operDesc = "用户信息获取")
    @GetMapping("/loggeduser")
    @ApiOperation(value = "用户信息获取", notes = "获取登录用户信息")
    public PlatformResponse<Map<String, Object>> getInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            throw PlatformException.error("token不能为空");
        }
        String username = JwtHelper.parseToken(token);
        //兼容oaToken
        if (Strings.isBlank(username)) {
            username = userService.getUserNameByLdap(token);
        }
        User user = userService.info(username);

        Map<String, Object> data = new HashMap<>();

        if (user == null) {
            data.put("username", username);
            data.put("name", username);

        } else {
            data.put("id", user.getId());
            data.put("username", username);
            data.put("name", user.getName());
            //   data.put("clientId", user.getClientId());
            data.put("userType", user.getUserType());
            data.put("remark", user.getRemark());
            data.put("enabled", user.getEnabled());
            data.put("auths", user.getRoles().stream().map(role -> role.getName()).collect(Collectors.toList()));
        }
        return PlatformResponse.successData(data);
    }


    @GetMapping("/getUsrUrls")
    @ApiOperation(value = "用户信息获取", notes = "获取登录用户信息")
    public PlatformResponse<PlatformUserDto> getUsrUrls(HttpServletRequest request) {
        String token = request.getHeader("token");
        String workWechatLoginToken = request.getHeader("qywxLoginToken");
        if (Strings.isBlank(token) && Strings.isBlank(workWechatLoginToken)) {
            throw PlatformException.error("token不能为空");
        }
        String username = "";
        if (Strings.isBlank(workWechatLoginToken)){
            username = JwtHelper.parseToken(token);
            //兼容oaToken
            if (Strings.isBlank(username)) {
                username = userService.getUserNameByLdap(token);
            }
        } else {
            username = userService.getUsernameByWorkWechatLoginToken(workWechatLoginToken);
        }
        if (Strings.isBlank(username)) {
            return PlatformResponse.failedMsg("获取用户信息失败");
        }
        PlatformUserDto userDto = userService.getUsrUrls(username);
        return PlatformResponse.successData(userDto);
    }

    @PageAccessAnnotation(operMenu = "用户修改密码接口", operType = "用户修改密码接口", operDesc = "用户修改密码接口")
    @PostMapping("/changepwd")
    @ApiOperation(value = "用户修改密码接口", notes = "修改密码")
    public PlatformResponse<Void> changePassword(@RequestBody String password, HttpServletRequest request) throws Exception {
        JsonObject json = JsonParser.parseString(password).getAsJsonObject();
        String oldPassword = json.get("oldPassword") != null ? json.get("oldPassword").getAsString() : null;
        String newPassword = json.get("newPassword") != null ? json.get("newPassword").getAsString() : null;
        String confirmPassword = json.get("confirmPassword") != null ? json.get("confirmPassword").getAsString() : null;

        if (oldPassword == null || newPassword == null || confirmPassword == null) {
            return PlatformResponse.failedMsg("入参oldPassword, newPassword, confirmPassword必填");
        }
        oldPassword = RSAEncrypt.decrypt(oldPassword, PlatformConstant.RSA_PRIVATE_KEY);
        newPassword = RSAEncrypt.decrypt(newPassword, PlatformConstant.RSA_PRIVATE_KEY);
        confirmPassword = RSAEncrypt.decrypt(confirmPassword, PlatformConstant.RSA_PRIVATE_KEY);
        if (!newPassword.equals(confirmPassword)) {
            return PlatformResponse.failedMsg("两次输入的密码不一致");
        }
        if (newPassword.isEmpty() || confirmPassword.isEmpty()) {
            return PlatformResponse.failedMsg("新密码不能为空");
        }


        String username = JwtHelper.parseToken(request.getHeader("token"));
        //兼容oaToken
        if (Strings.isBlank(username)) {
            username = userService.getUserNameByLdap(request.getHeader("token"));
        }
        PlatformUserDto user = userService.findByUsername(username);
        if (user == null) {
            return PlatformResponse.failedMsg("未找到账户: " + username);
        }
        if (!oldPassword.equals(user.getPassword())) {
            return PlatformResponse.failedMsg("旧密码验证失败");
        }
        userService.updatePassword(user.getId(), AESEncrypt.encrypt(newPassword));

        return PlatformResponse.successMsg("更新密码成功");
    }

    @PageAccessAnnotation(operMenu = "重置密码", operType = "重置密码", operDesc = "重置密码")
    @PostMapping("/resetpwd")
    @ApiOperation(value = "重置密码")
    public PlatformResponse<Void> resetPassword(@RequestBody String password, HttpServletRequest request) throws Exception {
        JsonObject json = JsonParser.parseString(password).getAsJsonObject();
        Long userId = json.get("userId") != null ? json.get("userId").getAsLong() : null;
        String newPassword = json.get("newPassword") != null ? json.get("newPassword").getAsString() : null;
        String confirmPassword = json.get("confirmPassword") != null ? json.get("confirmPassword").getAsString() : null;

        if (userId == null || newPassword == null || confirmPassword == null) {
            return PlatformResponse.failedMsg("入参userId, newPassword, confirmPassword必填");
        }
        if (!newPassword.equals(confirmPassword)) {
            return PlatformResponse.failedMsg("两次输入的密码不一致");
        }
        if (newPassword.isEmpty() || confirmPassword.isEmpty()) {
            return PlatformResponse.failedMsg("新密码不能为空");
        }

        //TODO 是否需要限制只有admin账户才能重置密码
//        String username = JwtHelper.parseToken(request.getHeader("token"));

        newPassword = RSAEncrypt.decrypt(newPassword, PlatformConstant.RSA_PRIVATE_KEY);

        User user = userService.findById(userId);
        if (user == null) {
            return PlatformResponse.failedMsg("未找到id=" + userId + "的账户");
        }
        userService.updatePassword(user.getId(), newPassword);

        return PlatformResponse.successMsg("重置密码成功");
    }


    /**
     * @param jsonResult
     * @return
     * @Description 處理返回token
     */
    public String parseToken(String jsonResult) {
        JSONObject jsonObject = JSON.parseObject(jsonResult);
        String codeNumber = jsonObject.getString(PlatformConstant.RETURN_CODE_KEY);
        if (codeNumber.equals(PlatformConstant.SUCCESS)) {
            JSONObject objectData = jsonObject.getJSONObject(PlatformConstant.RETURN_DATA_KEY);
            String token = objectData.getString(PlatformConstant.RETURN_TOK_KEY);
            return token;
        } else {
            return PlatformConstant.RETURN_TOK_ERROR;
        }
    }


    /**
     * @param usrJson
     * @return
     * @Description 根据JSON 解析UserName
     */
    public String getUserName(String usrJson) {

        JSONObject jsonObject = JSON.parseObject(usrJson);
        String codeNumber = jsonObject.getString(PlatformConstant.RETURN_CODE_KEY);

        if (codeNumber.equals(PlatformConstant.SUCCESS)) {
            JSONObject objectData = jsonObject.getJSONObject(PlatformConstant.RETURN_DATA_KEY);
            String userName = objectData.getString(PlatformConstant.RETURN_USERNAME_KEY);
            return userName;
        } else {
            return PlatformConstant.TOKEN_OVERDUE;
        }
    }


    @PostMapping("/loginPortal")
    public PlatformResponse<Map<String, String>> loginPortal(@RequestBody LoginUserDto userDto, HttpServletRequest request) throws Exception {

        String rightCode = (String) request.getSession().getAttribute("rightCode");
        String tryCode = userDto.getTryCode();
        if (StringUtils.isEmpty(rightCode) || StringUtils.isEmpty(tryCode) || !rightCode.equals(tryCode)) {
            return PlatformResponse.failedMsg("验证码错误");
        }
        if (ldapService.checkInterfaceParams(userDto, PlatformConstant.LOGIN_PORTAL_CODE)) {
            String password = RSAEncrypt.decrypt(userDto.getPassword(), PlatformConstant.RSA_PRIVATE_KEY);
            Boolean authorityResult = ldapService.checkUserAuthority(userDto.getUserName(), password);
            if (authorityResult) {
                Map<String, String> tokenMap = ldapService.getUserToken(userDto.getUserName(), userDto.getSystemId());
                return PlatformResponse.successData(tokenMap);

            } else {
                return PlatformResponse.failedMsg("用户密码错误");
            }
        } else {
            return PlatformResponse.failedMsg("缺失必要参数");
        }
    }

    @PostMapping("/setUserMenuData")
    @ApiOperation(value = "设置用户常用菜单数据")
    public PlatformResponse<Void> setUserData(@RequestBody String data, HttpServletRequest request) {
        String userName = JwtHelper.parseToken(request.getHeader("token"));
        //兼容oaToken
        if (Strings.isBlank(userName)) {
            userName = userService.getUserNameByLdap(request.getHeader("token"));
        }
        JsonObject json = JsonParser.parseString(data).getAsJsonObject();
        JsonElement menuDataE = json.get("menuData");

        if (menuDataE == null) {
            return PlatformResponse.failedMsg("入参menudata必填");
        }
        String menudata = menuDataE.toString();
        UserMenuInfo userMenuInfo = userService.findByUserName(userName);

        if (userMenuInfo == null) {
            userMenuInfo = new UserMenuInfo();
            userMenuInfo.setUserName(userName);
        }
        userMenuInfo.setMenuData(menudata);
        userService.save(userMenuInfo);
        return PlatformResponse.successMsg("设置用户菜单数据成功");
    }

    @GetMapping("/getUserMenuData")
    @ApiOperation(value = "获取用户常用菜单数据")
    public PlatformResponse<Map<String, Object>> getUserData(HttpServletRequest request, HttpServletResponse response) {
        String userName = JwtHelper.parseToken(request.getHeader("token"));
        //兼容oaToken
        if (Strings.isBlank(userName)) {
            userName = userService.getUserNameByLdap(request.getHeader("token"));
        }
        UserMenuInfo userMenuInfo = userService.findByUserName(userName);
        Map<String, Object> data = new HashMap<>();
        if (userMenuInfo == null) {
            return PlatformResponse.failedMsg("username have not menu");
        }
        data.put("id", userMenuInfo.getId());
        data.put("username", userName);
        data.put("menuData", userMenuInfo.getMenuData());

        return PlatformResponse.successData(data);
    }

    @GetMapping("/getOaLinkWithSSOToken")
    @ApiOperation(value = "根据网关SSOToken获取跳转oa流程链接", notes = "根据网关SSOToken获取跳转oa流程链接")
    public PlatformResponse<OaLinkDto> getOaLinkWithSSOToken(HttpServletRequest request, String requestId) {
        String gatewaySSOToken = request.getHeader("token");
        logger.info("从请求头获取到的Token:" + gatewaySSOToken);
        String username = JwtHelper.parseToken(gatewaySSOToken);
        //兼容oaToken
        if (Strings.isBlank(username)) {
            username = userService.getUserNameByLdap(gatewaySSOToken);
        }
        return PlatformResponse.successData(userService.getOaLinkWithSSOToken(gatewaySSOToken, requestId, username));
    }

}
